from iClouds.apiSerializers import *
from iClouds.apiAuthentication import *
from django.db.models import Q


class UserPassLoginSerializer(serializers.Serializer):
    """用户登录序列化"""

    username = CharField(label="用户名", help_text="用户名")
    password = CharField(label="密码", help_text="密码")
    token = CharField(read_only=True, label="Token", help_text="Token")

    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")
        try:
            user = AllinpayUserUserList.objects.get(
                Q(username=username) | Q(phone=username) | Q(email=username),
                password=password,
            )
        except BaseException as err:
            user = None

        if user is None:
            raise serializers.ValidationError("用户名或密码错误")
        if not user.status:
            raise serializers.ValidationError("用户已被禁用")

        token = get_tokens_for_user(user)
        attrs["token"] = f'Bearer {token["access"]}'

        return attrs


class QiniuUploadListSerializer(serializers.ModelSerializer):
    """七牛上传序列化"""

    header = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="资源路径"
    )
    cover = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="封面"
    )
    answer = CharField(read_only=True, help_text="上传者")
    creattime = DateTimeField(read_only=True, help_text="上传时间")

    users = SerializerMethodField()

    class Meta:
        model = AllinpayUploadList
        fields = ["header", "answer", "creattime", "users", "cover"]

    def get_users(self, attr):
        try:
            r = AllinpayUserUserList.objects.get(id=attr.answer)
        except BaseException as err:
            return ""
        else:
            return r.nicename

    def validate_header(self, attr):
        url = f"http://oss.3vppt.com/{attr}"
        return url


class AllinpayUploadListSerializer(serializers.ModelSerializer):
    """本地上传序列化"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="名称",
    )
    info = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="描述",
    )
    sorth = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="分类",
    )
    filename = CharField(read_only=True, help_text="原始文件名")
    header = CharField(read_only=True, help_text="路径")
    answer = CharField(read_only=True, help_text="上传者")
    creattime = DateTimeField(read_only=True, help_text="上传时间")
    cover = CharField(read_only=True, help_text="封面")

    users = SerializerMethodField()

    class Meta:
        model = AllinpayUploadList
        fields = "__all__"

    def get_users(self, attr):
        try:
            r = AllinpayUserUserList.objects.get(id=attr.answer)
        except BaseException as err:
            return ""
        else:
            return r.nicename


# ======================================================================


class YlWxCourseSerializer(serializers.ModelSerializer):
    id = IntegerField(label="ID", read_only=True)
    name = CharField(allow_blank=True, allow_null=True, max_length=255, required=False)
    content = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        style={"base_template": "textarea.html"},
    )
    price = DecimalField(
        allow_null=True, decimal_places=2, max_digits=10, required=False
    )
    time = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        style={"base_template": "textarea.html"},
    )
    user_id = IntegerField(allow_null=True, required=False)
    parent = IntegerField(allow_null=True, required=False)

    course = SerializerMethodField()

    class Meta:
        model = YlWxCourse
        fields = "__all__"

    def get_course(self, value):
        try:
            r = YlWxPlatformCourse.objects.get(id=value.parent)
        except BaseException as err:
            return ""
        else:
            return r.name

    def validate_parent(self, value):
        try:
            r = YlWxPlatformCourse.objects.get(id=int(value))
        except BaseException as err:
            raise serializers.ValidationError("展会活动ID不存在")
        return value


class YlWxPlatformCourseSerializer(serializers.ModelSerializer):
    id = IntegerField(label="ID", read_only=True)
    name = CharField(allow_blank=True, allow_null=True, max_length=255, required=False)
    content = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        style={"base_template": "textarea.html"},
    )
    time = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        style={"base_template": "textarea.html"},
    )
    user_id = IntegerField(allow_null=True, required=False)
    parent = IntegerField(allow_null=True, required=False)

    school = SerializerMethodField()

    class Meta:
        model = YlWxPlatformCourse
        fields = "__all__"

    def get_school(self, value):
        try:
            r = YlWxSchoolGroup.objects.get(id=value.parent)
        except BaseException as err:
            return ""
        else:
            return r.name

    def validate_parent(self, value):
        try:
            r = YlWxSchoolGroup.objects.get(id=int(value))
        except BaseException as err:
            raise serializers.ValidationError("场所ID不存在")
        return value


class YlWxSchoolGroupSerializer(serializers.ModelSerializer):
    id = IntegerField(label="ID", read_only=True)
    name = CharField(allow_blank=True, allow_null=True, max_length=255, required=False)
    pid = IntegerField(allow_null=True, required=False)
    user_id = IntegerField(allow_null=True, required=False)

    school = SerializerMethodField()

    class Meta:
        model = YlWxSchoolGroup
        fields = "__all__"

    def get_school(self, value):
        try:
            r = YlWxSchoolGroup.objects.get(id=value.pid)
        except BaseException as err:
            return ""
        else:
            return r.name

    def validate_pid(self, value):
        if not value:
            return value
        try:
            r = YlWxSchoolGroup.objects.get(id=int(value))
        except BaseException as err:
            raise serializers.ValidationError("场所ID不存在")
        return value


# =============================================================
# 名画也疯狂
# =============================================================


class postAniPortraitSerializer(serializers.Serializer):
    source_video = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="视频文件路径(1111.mp4)",
    )
    ref_img = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="模板文件(C9a4VI6v9NqY.jpeg)",
    )
    size = IntegerField(
        max_value=768, min_value=512, default=512, help_text="图像分辨率"
    )
    steps = IntegerField(max_value=25, min_value=25, default=25, help_text="fps")
    length = IntegerField(max_value=510, min_value=0, default=60, help_text="帧数")
    seed = IntegerField(max_value=42, min_value=42, default=42, help_text="播放速度")

    class Meta:
        fields = "__all__"


class playAniPortraitSerializer(serializers.Serializer):
    vid = IntegerField(help_text="视频ID")
    screen = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="大屏ID",
    )

    class Meta:
        fields = "__all__"

    def validate_vid(self, value):
        try:
            r = AllinpayUploadList.objects.get(id=int(value))
        except BaseException as err:
            raise serializers.ValidationError("该视频不存在")
        return value


class listAniPortraitSerializer(serializers.Serializer):
    screen = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        help_text="大屏ID",
    )

    class Meta:
        fields = "__all__"


class AllinpayUserPowerSerializer(serializers.ModelSerializer):
    id = IntegerField(label="ID", read_only=True)
    # form = ChoiceField(choices=("Image", "Audio", "Video"), help_text="资源类型")
    form = CharField(allow_blank=True,allow_null=True,max_length=255,help_text="资源类型")
    url = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        validators=[UniqueValidator(queryset=AllinpayUserPower.objects.all())],
        help_text="资源地址",
    )
    answer = IntegerField(
        read_only=True,
        help_text="拥有者",
    )
    current = DateTimeField(read_only=True, help_text="创建时间")

    class Meta:
        model = AllinpayUserPower
        fields = "__all__"


# print(repr(AllinpayUserPowerSerializer()))
